package soar.template.spring.websocket.chat.configuration;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.stereotype.Component;

import com.mchange.v2.c3p0.ComboPooledDataSource;

@Configuration
public class MySQL
{
    @Autowired
    private MySQLPropertiesMain mysqlPropertiesMain;

    @Bean
    @Primary
    public DataSource datasourceMain() throws Exception
    {
        ComboPooledDataSource ds = new ComboPooledDataSource();
        ds.setDriverClass("com.mysql.jdbc.Driver");
        ds.setJdbcUrl(mysqlPropertiesMain.getUrl());
        ds.setUser(mysqlPropertiesMain.getUsername());
        ds.setPassword(mysqlPropertiesMain.getPassword());
        ds.setMaxPoolSize(100);
        ds.setMaxIdleTime(20);
        return ds;
    }

    @Bean(name = "emfMain")
    @Primary
    public LocalContainerEntityManagerFactoryBean emfMain() throws Exception
    {
        HibernateJpaVendorAdapter vendor = new HibernateJpaVendorAdapter();
        vendor.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");
        vendor.setGenerateDdl(false);
        vendor.setShowSql(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setPersistenceUnitName("main");
        factory.setDataSource(datasourceMain());
        factory.setJpaVendorAdapter(vendor);
        Properties props = new Properties();
        props.put("hibernate.format_sql", "true");
        props.put("hibernate.hbm2ddl.auto", "validate");
        factory.setJpaProperties(props);

        return factory;
    }

}

class MySQLProperties
{
    protected String url;
    protected String username;
    protected String password;

    public String getUrl()
    {
        return url;
    }

    public void setUrl(String url)
    {
        this.url = url;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

}

@Component
@ConfigurationProperties("mysql.main")
class MySQLPropertiesMain extends MySQLProperties
{

}
